package com.wgts.wgts.control.recycleview;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.wgts.wgts.R;

public abstract  class BaseLoadMoreAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    /**
     * true为没有更多了， false 为有更多;
     */
    protected boolean noMore;

    private static final int NO_MORE = 0xFeFeFe;

    private static final int BODY = 0xeFeFeF;

    private Context context;

    public BaseLoadMoreAdapter(Context context) {
        this.context = context;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        if(i == NO_MORE){

            NoMoreViewHolder viewHolder = new NoMoreViewHolder(LayoutInflater.from(context).inflate(R.layout.no_more, viewGroup, false));

            if(getBodyItemCount() > 20){
                viewHolder.itemView.setVisibility(View.VISIBLE);
            }else{
                viewHolder.itemView.setVisibility(View.GONE);
            }

            return viewHolder;
        }
        return onCreateBodyViewHolder(viewGroup, i);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
        if(i < getBodyItemCount()){
            onBindBodyViewHolder((VH)viewHolder, i);
        }
    }

    public abstract void onBindBodyViewHolder(@NonNull VH viewHolder, int i);

    @NonNull
    public abstract  VH onCreateBodyViewHolder(@NonNull ViewGroup viewGroup, int i);

    @Override
    public int getItemCount() {
        if(getBodyItemCount() == 0){
            return getBodyItemCount();
        }

        if(noMore){
            return getBodyItemCount() + 1;
        }

        return getBodyItemCount();
    }

    @Override
    public int getItemViewType(int position) {
        if(noMore){
            if(position == getItemCount() - 1){
                return NO_MORE;
            }
        }

        if(position < getBodyItemCount()){
            return getBodyItemViewType(position);
        }
        return BODY;
    }

    public abstract int getBodyItemCount();


    public void setNoMore(boolean noMore) {
        this.noMore = noMore;
    }

    public class NoMoreViewHolder extends RecyclerView.ViewHolder {

        public View itemView;

        public NoMoreViewHolder(@NonNull View itemView) {
            super(itemView);
            this.itemView = itemView;
        }
    }

    public abstract int getBodyItemViewType(int position);
}
